﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;
using CKS.PLC.Core.Cache;
using FreeSql;
using Infrastructure;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZR.Infrastructure;
using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP90
{
    /// <summary>
    /// 动作编号
    ///  1 热处理开始请求
    /// </summary>
    public class DB3011_Work01Action : PLCAction
    {
        
        public DB3011_Work01Action(DecodeValue _value) : base(_value)
        {
           
        }
        public override void Execute()
        {
            var replayDB = 3010;
            var replayAction = 10;
            var result = Value.Value.ToInt();
            
            var replayPos = Value.GetPosition(replayDB, replayAction, 0);
         
            if (result == 1)
            {
                /*
                 创建热处理记录表 cks_heat_treatment
                 料架信息 开始时间 结束时间 状态 1开始 10完成 ， 创建时间
                 
                 */
                var model = conn.Select<CksHeatTreatment>().OrderByDescending(a => a.Id).First();
                if (model == null || model.Status == 10  )
                {
                    var time = DateTime.Now;
                     model = new CksHeatTreatment()
                    {
                        BatchNo = IdHelper.GetNextNo(),
                        CreatedTime = time,
                        StartTime = time,
                        ShelfCode1 = Value.GetLinkData(1).ToInt(),
                        ShelfCode2 = Value.GetLinkData(2).ToInt(),
                        Status = 1
                    };
                    conn.Insert(model).ExecuteAffrows();

                    //保存数据到动态表、
                   var palletizerCells1 = conn.Select<CksShelfPalletizer>().Where(a=>a.ShelfId == model.ShelfCode1   ).ToList();
                   var palletizerCells2 = conn.Select<CksShelfPalletizer>().Where(a => a.ShelfId == model.ShelfCode2).ToList();

                    if(model.Status == 1)
                    {
                        SaveProductInfo(model,palletizerCells1);
                        SaveProductInfo(model,palletizerCells2);
                    }
                    
                }
                EventBus.AddLog("OP90热处理开始请求");
                AckWriteInt16(replayPos, 1);
            }
            else
            {
               
                AckWriteInt16(replayPos, 0);
                logger.LogInformation($"OP90开始热处理-确认信号重置");
            }
        }

        private void SaveProductInfo( CksHeatTreatment main,List<CksShelfPalletizer> palletizerCells)
        {
            foreach (var item in palletizerCells)
            {
                if(!item.CoverCode.IsEmpty())
                {
                    //码不为空存入OP90_Data表
                    var vt =conn.Select<CksVirtualTable>().Where(a => a.TableName == "OP90_Data").First();
                    var columnQuery = conn.Select<CksVirtualColumn>().Where(a => a.TableId == vt.Id).OrderBy(a => a.Sequence);
                    var columns = columnQuery.ToList();
                    var table = ServiceCommon.GetFreesqlTableInfo(vt, columns);
                    var dict = new Dictionary<string, object>();
                    dict["CoverCode"] = item.CoverCode;
                    dict["ShelfCode"] = item.ShelfId;
                    dict["BatchNo"] = main.BatchNo;
                    dict["CreatedTime"] = DateTime.Now;
                    dict["Nullity"] = false;
                    dict["IsDeleted"] = false;
                    object obj =table.CreateInstance(dict);
                    dict["Id"] = conn.Insert<object>().AsType(table.Type).AppendData(obj).ExecuteIdentity(); //保存到动态表
                   

                }
            }
        }
    }
}
